# 判断pdf文件是否损坏，损坏的将目录和名称打印出来并删除
import PyPDF2
import os
import re


# 参数为pdf文件全路径名，文件有效返回true,无效返回false
def isValidPDF_pathfile(pathfile):
    bValid = True
    try:
        # PdfFileReader(open(pathfile, 'rb'))
        reader = PyPDF2.PdfFileReader(pathfile, strict=False)
        # if reader.getNumPages() < 1:  # 进一步通过页数判断。
        #     bValid = False
    except Exception as e:
        bValid = False
        print(pathfile + '文件已损坏' + str(e))
    return bValid


def file_name(file_dir, i):
    for root, dirs, files in os.walk(file_dir, topdown=False):
        print(root)  # 当前目录路径
        for pdffile in files:
            res_tr = r'''f.*?\.pdf'''  # 从网页源码中获取字符的正则表达式
            re_tr = re.findall(res_tr, pdffile, re.S)  # 利用正则表达式获取字符串并存到链表
            if len(re_tr):
                pdffilepath = root + '\\' + pdffile
                pdfright = isValidPDF_pathfile(pdffilepath)
                if not pdfright:
                    with open('D:/GlobalLawFiles/pdferror.txt', 'a', encoding='utf-8') as f:
                        i = i + 1
                        f.write(str(i) + '    ' + pdffilepath + '\n')
                    if os.path.exists(pdffilepath):
                        os.remove(pdffilepath)
                continue


path = r"E:\工作记录\工作内容\“一带一路”项目\各国专家提供的法律资源资料\缅甸\jurisprudence_1948"
pdffilepath = r'''E:\工作记录\工作内容\“一带一路”项目\各国专家提供的法律资源资料\缅甸\jurisprudence_1948\jurisprudence_1948.pdf'''
pdfright = isValidPDF_pathfile(pdffilepath)
n = 0
file_name(path, n)
with open('D:/GlobalLawFiles/pdferror.txt', 'a', encoding='utf-8') as file:
    file.write('清洗结束\n')

